package com.lilicould.service;

import com.google.gson.Gson;
import com.lilicould.dao.GradeDao;
import com.lilicould.entity.GradeDetails;
import com.lilicould.entity.Grades;
import com.lilicould.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class GradeService {

    // 根据学号查询成绩
    public String getGradesByUserNo(String userNo) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            GradeDao gradeDao = sqlSession.getMapper(GradeDao.class);
            List<GradeDetails> result = gradeDao.getGradesByUserNo(userNo);
            if (result != null) {
                return new Gson().toJson(result);
            } else {
                return null;
            }
        }catch (Exception e) {
            return null;
        }
    }

    // 根据课程安排ID查询成绩
    public String getGradesByScheduleId(int scheduleId) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            // 获取映射器对象
            GradeDao gradeDao = sqlSession.getMapper(GradeDao.class);
            // 根据课程安排ID查询成绩
            List<GradeDetails> result = gradeDao.getGradesByScheduleId(scheduleId);
            if (result != null) {
                // 返回查询结果
                return new Gson().toJson(result);
            } else {
                return null;
            }
        }catch (Exception e) {
            return null;
        }
    }

    public String addGrades(List<Grades>  grades) {
        Gson gson = new Gson();
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            GradeDao gradeDao = sqlSession.getMapper(GradeDao.class);
            for (Grades grade : grades) {
                int result;
                if (grade.getId()!= null) {
                    // 如果是修改数据，则修改
                    result = gradeDao.updateGrade(grade);
                } else {
                    // 如果是新增数据，则添加
                    result = gradeDao.addGrade(grade);
                }
                if (result <= 0){
                    // 添加失败，直接返回错误信息
                    return gson.toJson("存在数据添加失败，请检查是否有数值或输入错误");
                }
            }
            // 若所有添加成功，则提交事务
            sqlSession.commit();
            return null;
        }catch (Exception e) {
            return gson.toJson(e.getMessage());
        }
    }
}
